#include <QLocale>
#include "abstract-database-client.h"
#include "model-result.h"
#include "order-item-addition-model.h"
#include "order-item-addition-queries.h"
#include "standard-table-model.h"

OrderItemAdditionModel::OrderItemAdditionModel(QObject *parent) :
    StandardDatabaseModel(parent)
{
    m_idColumnCount = 2;
}

void OrderItemAdditionModel::initialize()
{
    m_queries = new OrderItemAdditionQueries(this);
    m_headerSections << "Nazwa" << "Cena" << "VAT" << "Ilość" << "Magazyn";
    StandardDatabaseModel::initialize();
}

void OrderItemAdditionModel::setupInternalModel()
{
    StandardDatabaseModel::setupInternalModel();

    for (int i = 0; i < rowCount(); i++)
    {
        // sum column
        QString price = QLocale().toString(m_internalModel->index(i, PriceColumn+m_idColumnCount).data().toDouble(), 'f', 2);
        m_internalModel->setData(m_internalModel->index(i, PriceColumn+m_idColumnCount), price, Qt::DisplayRole);
    }

    StandardTableModel* internalModel = qobject_cast<StandardTableModel*>(m_internalModel);
    QVariantList warehouseIds;
    for (int i = 0; i < m_warehouseModel->rowCount(); i++)
        warehouseIds << m_warehouseModel->index(i, 0).data();
    internalModel->insertColumn(1, warehouseIds);

    QVariantList warehouseNames;
    for (int i = 0; i < m_warehouseModel->rowCount(); i++)
        warehouseNames << m_warehouseModel->index(i, 1).data();
    internalModel->appendColumn(warehouseNames);
    delete m_warehouseModel;
}

void OrderItemAdditionModel::loadData()
{
    // znajdź produkty poza zamówieniem
    // 1. wyszukaj Poz_zam takie, że id_zam równe id zamówienia
    // 2. wyszukaj wszystkie Prod_mag
    // 3. przefiltruj Prod_mag, usuwając rekordy z id_prod z Poz_zam
    // 4. wyszukaj Produkty takie, że id = id_prod (multizapytanie)
    // 5. wyszukaj Magazyny takie, że id = id_mag (multizapytanie)
    // 6. schowaj id, pozamieniaj miejscami kolumny, dodaj kolumnę nazwy magazynu
    // 7. przy dodawaniu prześlij id_mag, id_zam, id_prod, vat, ilosc, nazwa, cena_jed

    ModelResult* result = m_databaseClient->selectModel(m_queries->selectQuery(0, 0), m_loadingParameters);
    connect (result, &ModelResult::resultReady, this, &OrderItemAdditionModel::continueLoadData);
}

void OrderItemAdditionModel::continueLoadData (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    m_orderItemModel = result->model();
    m_orderItemModel->setParent(this);

    QString selectQuery = m_queries->selectQuery(1, 0);
    ModelResult* newResult = m_databaseClient->selectModel(selectQuery);
    connect (newResult, &ModelResult::resultReady, this, &OrderItemAdditionModel::continueLoadData2);
}

void OrderItemAdditionModel::continueLoadData2 (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    m_productInWarehouseModel = result->model();
    m_productInWarehouseModel->setParent(this);
    for (int i = 0; i < m_orderItemModel->rowCount(); i++)
    {
        QVariant id = m_orderItemModel->index(i, 3).data();
        for (int j = 0; j < m_productInWarehouseModel->rowCount(); j++)
        {
            if (m_productInWarehouseModel->index(j, 2).data() == id)
            {
                m_productInWarehouseModel->removeRow(j);
                break;
            }
        }
    }
    delete m_orderItemModel;

    QVariantList parameters;
    for (int i = 0; i < m_productInWarehouseModel->rowCount(); i++)
        parameters << m_productInWarehouseModel->index(i, 1).data();

    QString selectQuery = m_queries->selectQuery(2, parameters.size());
    ModelResult* newResult = m_databaseClient->selectModel(selectQuery, parameters);
    connect (newResult, &ModelResult::resultReady, this, &OrderItemAdditionModel::continueLoadData3);
}

void OrderItemAdditionModel::continueLoadData3 (ModelResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd ładowania danych", result->error().text());
        return;
    }

    m_warehouseModel = result->model();
    m_warehouseModel->setParent(this);

    QVariantList parameters;
    for (int i = 0; i < m_productInWarehouseModel->rowCount(); i++)
        parameters << m_productInWarehouseModel->index(i, 2).data();
    delete m_productInWarehouseModel;

    QString selectQuery = m_queries->selectQuery(3, parameters.size());
    ModelResult* newResult = m_databaseClient->selectModel(selectQuery, parameters);
    connect (newResult, &ModelResult::resultReady, this, &OrderItemAdditionModel::finishLoadData);
}
